package com.example.whm;



import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.ArrayAdapter;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.ListPopupWindow;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.TextView;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioGroup;
import cn.db.Msg;

import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.example.whm.lib.Service_;
import com.example.whm.lib.box_Selection;
import com.example.whm.model.Address;
import com.example.whm.model.Order;
import com.example.whm.model.PreOrder;
import com.example.whm.model.User;
import com.koushikdutta.async.http.WebSocket;


public class FlowCreate extends Activity implements OnClickListener{

	private AQuery aq; 
	private AQuery aq2;
	
	private String topic;
	Address add;
	Map<String, String> map;
	List<Order> boxs;
	int num=0;
	int price=0;
	int tag;
	box_Selection mCallback;
	ListPopupWindow popup;
	
	RadioGroup radioButtonGroup;
	ProgressDialog dialog;
	adapter adap;
	TextView num_t;
	TextView price_t;
	List<CheckBox> check_list=new ArrayList<CheckBox>();
	PreOrder order;
	Service_ ser;
	WebSocket w;
	SharedPreferences sp;
	User user;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setTheme(R.style.Holo_Theme_Light); 
		
		//setTheme(R.style.StyledIndicators); 
		//getSupportActionBar().hide();
		
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		// setSupportProgressBarVisibility(false);
		setContentView(R.layout.flow_create);
		aq = new AQuery(this);
		
		aq.id(R.id.flow_create_btn).clicked(FlowCreate.this);
		bindService(new Intent(this, Service_.class), conn, Context.BIND_AUTO_CREATE);
		
	    sp=((Application)getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
	    user=JSONObject.parseObject(sp.getString("user",null), User.class);
		
	}

	
	
	Handler handle=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {  
		    case 1:
		    	Msg m=(Msg) msg.obj;
		    	adap.getList().add(m);
		    	adap.notifyDataSetChanged();
		    	break;
		    default:  
		        break;  
		    }	
		}
		
		
	};
	
	

	
	
	
	






	ListView list;
/*public void init(){
	
	  String url="http://"+Whm_app.api_url+":9000/api/user_order";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);
  }

  public void ui(){
	
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
			
				  
				 runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						
						  aq.id(R.id.progress).gone();
						//  aq2.id(R.id.four_layout_line).visible();
						  
						//   list=(ListView) aq2.id(R.id.myorder_fragment_listview).getListView();
						  View v=FlowCreate.this.getLayoutInflater().inflate(R.layout.mypreorder_detail_footview, null);
						  AQuery a=new AQuery(v);
						 
						  a.id(R.id.myorder_detail_foot_area).text(order.getCity_area());
						  a.id(R.id.myorder_detail_foot_address).text(order.getAddress());
						  a.id(R.id.myorder_detail_foot_contactname).text(order.getContactname());
						  a.id(R.id.myorder_detail_foot_phone).text(order.getPhone());
						  aq.id(R.id.myorder_detail_listview).getListView().addFooterView(v);
						    View v2=FlowCreate.this.getLayoutInflater().inflate(R.layout.four_layout_footer, null);
						   AQuery a=new AQuery(v);
						  AQuery a2=new AQuery(v2);
						  a.id(R.id.four_layout_contact_name).text(add.getContact_name());
						  a.id(R.id.four_layout_contact_phone).text(add.getPhone());
						  a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
						  a2.find(R.id.four_layout_btn_sure).clicked(MyOrderFragment.this); 
						   radioButtonGroup=(RadioGroup) a.find(R.id.four_layout_pay).getView();
						  list.addHeaderView(v);
						  list.addFooterView(v2);
						 
						  adap=new adapter(order.getList());
						  aq.id(R.id.myorder_detail_listview).adapter(adap);						 
						  //Utility.setListViewHeightBasedOnChildren(list);
					  }
				  });
			  }
		  }).start();
			
		  
	
	  
  }
*/
  
  
  
  
  
  
  
  class adapter extends BaseAdapter{

		
		List<Msg> list;
		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		
		public List<Msg> getList() {
			return list;
		}



		public void setList(List<Msg> list) {
			this.list = list;
		}



		public adapter(List<Msg> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.flow_listview_item, arg2);
			}
			
			
			Msg i = (Msg) getItem(arg0);
			//System.out.println("JSONObject.toJSONString(i)===="+JSONObject.toJSONString(i));
			AQuery aq2 = aq.recycle(arg1);
			//aq2.id(R.id.flow_listview_item_author).text(String.valueOf(i.getNum()));
			aq2.id(R.id.flow_listview_item_author).text(i.getFrom());	
			aq2.id(R.id.flow_listview_item_date).text(i.getTime());
			aq2.id(R.id.flow_listview_item_cont).text(i.getContent());
			//String tbUrl = i.getEntity().getPre_pic().replace("localhost", Whm_app.api_url);
			//String tbUrl = i.getImg_url();
		
			//System.out.println("tbUrl=================="+tbUrl);
			//Bitmap placeholder = aq.getCachedImage(R.drawable.image_ph);
			//Bitmap bit=aq.getCachedImage(R.drawable.ic_launcher);
			/*if(aq2.shouldDelay(arg0, arg1, arg2, tbUrl)){
						
				//aq.id(R.id.two_f_i_image).image(bit);
				aq2.id(R.id.two_f_i_image).clear();
				
			}else{
				
				//aq.id(R.id.two_f_i_image).image(tbUrl, true, true, 200, R.drawable.ic_launcher, bit, 0, 0);
				
				aq2.id(R.id.two_f_i_image).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null, 0, 0);
			}*/
		
			return arg1;
		}
		
		
	}
  
 
  public void showListPopup(View anchor) {
      popup = new ListPopupWindow(FlowCreate.this);
      popup.setAnchorView(anchor);
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(FlowCreate.this,android.R.layout.simple_list_item_2);  
      adapter.add("order");  
      adapter.add("preorder");  
      adapter.add("subscribe");    
      popup.setAdapter(adapter);
      ListView list=popup.getListView();
      
  //    popup.setWidth(300);
   //   popup.setHeight(400);
    // list.setOnItemSelectedListener();
      //list.setOnItemClickListener(FourFragmentOrder.this);
      //.setOnItemClickListener(FourFragmentOrder.this);
      
  }
  
  
  public void makeMenu(Menu menu, MenuInflater inflater) {
      if (menu instanceof ContextMenu) {
          ((ContextMenu) menu).setHeaderTitle("Context menu title");
      }
      menu.clear();
      inflater.inflate(R.menu.menu, menu);
      for (int i = 0; i < menu.size(); i++) {
          menu.getItem(i).setOnMenuItemClickListener(mOnMenuItemClickListener);
      }
     
  }
  
  private final OnMenuItemClickListener mOnMenuItemClickListener = new OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem menuItem) {
          boolean result = false;
          final int id = menuItem.getItemId();
          if (menuItem.getTitle().equals("order")) {
        	  mCallback.show_boxf(0);
		  }
          if (menuItem.getTitle().equals("preorder")) {       
        	  mCallback.show_boxf(1);
          }
          if (menuItem.getTitle().equals("subscribe")) {        	  
        	  mCallback.show_boxf(2);
          }
          //  System.out.println("onMenuItemClick id========="+id);
          return true;
      }
  };
  
 


public void show_dialog(boolean b){
	
	if (dialog==null) {
		dialog = new ProgressDialog(FlowCreate.this);
	    dialog.setIndeterminate(true);
	    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    dialog.setMessage("post");
	}
	if (b) {
		dialog.show();
	}else{
		dialog.dismiss();
	} 
    
}



@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	switch (v.getId()) {  
    case R.id.flow_create_btn:
    	String con=aq.id(R.id.flow_create_input).getText().toString();
    	
    	if (!con.trim().toString().equals("")) {
    		Msg m=new Msg(user.getName(), null, 2, 0, con, DateFormat.getDateTimeInstance().format(new Date()));
    		m.setTimemils(Calendar.getInstance().getTimeInMillis()); 
    		m.setFrom_u_avator(user.getAvator());
    		m.setFrom_u_id(user.getId());
    		
			String msg=JSONObject.toJSONString(m);			
			System.out.println(msg);
			w=ser.getW();
			//System.out.println("w==null -"+w.isOpen());
			if (w!=null&&w.isOpen()) {
				
				System.out.println("msg="+msg);
				w.send(msg);
				this.finish();
			}/*else{
				ser.init_websocket();
			}*/
			
		}
    	
    	
    	//buy_sure();
    	break;
    case R.id.four_layout_btn_all:
    	//btn_all();
    	break;

    	
    default:  
        break;  
    }  
}



private ServiceConnection conn = new ServiceConnection() {
    
    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub
    	
         ser = ((Service_.MyBinder)service).getService();
     
       	// ser.getHmap().put(FlowCreate.class.getSimpleName(), handle);	
        
        
        
    }
};

@Override
protected void onDestroy() {
	// TODO Auto-generated method stub
	super.onDestroy();
     unbindService(conn);
}	


    
 
}
